package com.ruoyi.project.setsystem.rolepower.service;


import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.project.setsystem.rolepower.domain.RolePower;
import com.ruoyi.project.setsystem.rolepower.mapper.RolePowerDeptMapper;
import com.ruoyi.project.setsystem.rolepower.mapper.RolePowerMapper;
import com.ruoyi.project.setsystem.rolepower.mapper.RolePowerMenuMapper;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.domain.RoleDept;
import com.ruoyi.project.system.role.domain.RoleMenu;
import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 大帅比
 * @date 2020-09-20 11:51
 * @desc 百战程序员 http://www.itbaizhan.com
 */
@Service
public class RolePowerServiceImpl implements IRolePowerService {
    @Autowired
    private RolePowerMapper rolePowerMapper;
    @Autowired
    private RolePowerDeptMapper rolePowerDeptMapper;
    @Autowired
    private RolePowerMenuMapper rolePowerMenuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<RolePower> All(RolePower rolePower) {


        return rolePowerMapper.All(rolePower);
    }
    @Override
    public Set<String> selectRoleKeys(Long userId)
    {
        List<RolePower> perms = rolePowerMapper.selectRolesByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (RolePower perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /*** 根据用户ID查询角色*/
    @Override
    public List<RolePower> selectRolesByUserId(Long userId)
    {
        List<RolePower> userRoles = rolePowerMapper.selectRolesByUserId(userId);
        List<RolePower> roles = selectRoleAll();
        for (RolePower rolePower : roles)
        {
            for (RolePower userRole : userRoles)
            {
                if (rolePower.getRoleId().longValue() == userRole.getRoleId().longValue())
                {
                    rolePower.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<RolePower> selectRoleAll()
    {
        return SpringUtils.getAopProxy(this).All(new RolePower());
    }

    /*** 通过角色ID查询角色*/
    @Override
    public RolePower selectRoleById(Long roleId)
    {
        return rolePowerMapper.selectRoleById(roleId);
    }

    /*** 通过角色ID删除角色*/
    @Override
    public boolean deleteRoleById(Long roleId)
    {
        return rolePowerMapper.deleteRoleById(roleId) > 0 ? true : false;
    }

    /*** 批量删除角色信息*/
    @Override
    public int deleteRoleByIds(String ids) throws BusinessException
    {
        Long[] roleIds = Convert.toLongArray(ids);
        for (Long roleId : roleIds)
        {
            checkRoleAllowed(new RolePower(roleId));
            RolePower rolePower = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0)
            {
                throw new BusinessException(String.format("%1$s已分配,不能删除", rolePower.getRoleName()));
            }
        }
        return rolePowerMapper.deleteRoleByIds(roleIds);
    }

    /*** 新增保存角色信息*/
    @Override
    @Transactional
    public int insertRole(RolePower rolePower)
    {
        rolePower.setCreateBy(ShiroUtils.getLoginName());
        // 新增角色信息
        rolePowerMapper.insertRole(rolePower);
        ShiroUtils.clearCachedAuthorizationInfo();
        return insertRoleMenu(rolePower);
    }

    /*** 修改保存角色信息*/
    @Override
    @Transactional
    public int updateRole(RolePower rolePower)
    {
        rolePower.setUpdateBy(ShiroUtils.getLoginName());
        // 修改角色信息
        rolePowerMapper.updateRole(rolePower);
        ShiroUtils.clearCachedAuthorizationInfo();
        // 删除角色与菜单关联
        rolePowerMenuMapper.deleteRoleMenuByRoleId(rolePower.getRoleId());
        return insertRoleMenu(rolePower);
    }


    /*** 新增角色菜单信息*/
    public int insertRoleMenu(RolePower rolePower)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<RoleMenu> list = new ArrayList<RoleMenu>();
        for (Long menuId : rolePower.getMenuIds())
        {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(rolePower.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = rolePowerMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }



    /*** 校验角色名称是否唯一*/
    @Override
    public String checkRoleNameUnique(RolePower rolePower)
    {
        Long roleId = StringUtils.isNull(rolePower.getRoleId()) ? -1L : rolePower.getRoleId();
        RolePower info = rolePowerMapper.checkRoleNameUnique(rolePower.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.ROLE_NAME_NOT_UNIQUE;
        }
        return UserConstants.ROLE_NAME_UNIQUE;
    }

    /*** 校验角色权限是否唯一*/
    @Override
    public String checkRoleKeyUnique(RolePower rolePower)
    {
        Long roleId = StringUtils.isNull(rolePower.getRoleId()) ? -1L : rolePower.getRoleId();
        RolePower info = rolePowerMapper.checkRoleKeyUnique(rolePower.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.ROLE_KEY_NOT_UNIQUE;
        }
        return UserConstants.ROLE_KEY_UNIQUE;
    }

    /*** 校验角色是否允许操作*/
    public void checkRoleAllowed(RolePower rolePower)
    {
        if (StringUtils.isNotNull(rolePower.getRoleId()) && rolePower.isAdmin())
        {
            throw new BusinessException("不允许操作超级管理员角色");
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /*** 角色状态修改*/
    @Override
    public int changeStatus(RolePower rolePower)
    {
        return rolePowerMapper.updateRole(rolePower);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(UserRole userRole)
    {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int deleteAuthUsers(Long roleId, String userIds)
    {
        return userRoleMapper.deleteUserRoleInfos(roleId, Convert.toLongArray(userIds));
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId 角色ID
     * @param userIds 需要删除的用户数据ID
     * @return 结果
     */
    public int insertAuthUsers(Long roleId, String userIds)
    {
        Long[] users = Convert.toLongArray(userIds);
        // 新增用户与角色管理
        List<UserRole> list = new ArrayList<UserRole>();
        for (Long userId : users)
        {
            UserRole ur = new UserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleMapper.batchUserRole(list);
    }
}
